package com.szmg.wishwalls.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {
	
	//每小时的毫秒数
	public static int HOUR_MILLI_SECOND = 60 * 60 *1000;
	
	/**
	 * 获取指定日后之后几天的日期
	 * 
	 * @param date
	 * @param i
	 * @return
	 */
	public static Date getDate(Date date, int i) {

		if (null == date)
			return null;

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DATE, i);

		return calendar.getTime();

	}
	
	public static Date getSystemDate(){
		return Calendar.getInstance().getTime();
	}
	
	/**
	 * 把日期对象转换成指定格式的字符串
	 * 
	 * @param dDate
	 *            - 日期对象
	 * @param sFormat
	 *            - 日期格式@return String yyyy-MM-dd HH:mm:ss
	 */
	public static String dateToStr(Date date, String sFormat) {		
		if (null == date)
			return "";
		
		SimpleDateFormat df = new SimpleDateFormat(sFormat);
		return df.format(date);
	}
	
	/**
	 * 根据年月得到输入月份的天数
	 * */
	 public static int getDays(int m, int n) {
	  int allday;
	  int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	  Calendar cal = Calendar.getInstance();
	  cal.set(Calendar.YEAR, m);
	  cal.set(Calendar.MONTH, n - 1);
	  cal.set(Calendar.DATE, 1);
	  if ((m % 4 == 0 && m % 100 != 0 || m % 400 == 0) && n == 2)
	   days[1]++;
	  allday = days[n - 1];
	  
	  return allday;
	 }
	 
	 /**
	  * 获取当月第一天
	  * @param sFormat
	  * @return
	  */
	 public static String getFirstDay(String sFormat){
		 
		 SimpleDateFormat df = new SimpleDateFormat(sFormat);
		 
		 Calendar cal = Calendar.getInstance();
	     cal.set(cal.DATE, 1);
	  
	     return df.format(cal.getTime());
	 }
	 
	 /**
	  * 获取当月最后一天
	  * @param sFormat
	  * @return
	  */
	 public static String getEndDay(String sFormat){
		 
		SimpleDateFormat df = new SimpleDateFormat(sFormat);
		 
		Calendar cal = Calendar.getInstance();
        // 当前月＋1，即下个月
        cal.add(cal.MONTH, 1);
        // 将下个月1号作为日期初始zhii
        cal.set(cal.DATE, 1);
        // 下个月1号减去一天，即得到当前月最后一天
        cal.add(cal.DATE, -1);
        
        return df.format(cal.getTime());
	 }
	 
	 public static Date stringToDate(String str,String format) {
			if (null == str || str.equals(""))
				return null;
			
			if(format==null || format.equals("")){
				format="yyyy-MM-dd HH:mm:SS";
			}
			
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			
			try {
				return sdf.parse(str);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			return null;
	}
	 
	/**
	 * date 为指定时间  2012-12-12 14:23:00,N为获取时间为N小时之后的时间
	 * @param date
	 * @param n
	 * @return
	 */
	public static Date getDateAffterHour(Date date,int n) {
		if(null == date) return null;
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(date.getTime() + n * DateUtil.HOUR_MILLI_SECOND);
		return c.getTime();
	}
	
	
}
